/*********************************************************************************
 *      Copyright:  (C) 2022 lijiale<244871365@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  main.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(14/01/22)
 *         Author:  lijiale<244871365@qq.com>
 *      ChangeLog:  1, Release initial version on "14/01/22 16:27:03"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>    
#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

#include "bc28_at.h"
#include "atcmd.h"
#include "comport.h"
#include "nbiot.h"
#include "zlog.h"

#define   DELAY_S         5


int     g_stop = 1;
int     g_report = 1;



void sig_handler(int signum)
{
    switch(signum)
    {
        case SIGINT:
        case SIGTERM:
            g_stop = 0;
            break;

        case SIGALRM:
            g_report = 1;
    }
}

void comport_init(comport_t *comport);

int main(int argc,char **argv)
{
	int				rv = 0;
	int				temp = 28;
	char				*port = "5683";
	char			*ip = "221.229.214.202";
	
    zlog_category_t *c;
	
    nbiot_hwinfo_t	hwinfo;
	comport_t		comport;
	
    signal(SIGINT,  sig_handler);
    signal(SIGTERM, sig_handler);
    signal(SIGALRM, sig_handler);
    
    rv = zlog_init("./zlog.conf");
    if( rv )
    {
        printf("zlog init failed\n");
        return -9;
    }

    c = zlog_get_category("my_cat");
    if( !c )
    {
        printf("get cat fail\n");
        zlog_fini();
        return -10;
    }
    printf("Initial zlog successfully\n");

    if( (daemon(0, 1)) < 0 )
    {
        printf("Deamon failed : %s\n", strerror(errno));
        goto OUT;

    }

	comport_init(&comport);
	
	if( find_nbiot_dev(&comport) < 0 )
	{
		zlog_error(c," main_find_nbiot_dev failure");
		rv = -1;
        goto OUT;
	}
	
	if( nbiot_module(&comport,&hwinfo) < 0 )
	{
		zlog_error(c,"main_get_hwinfo failure");
		rv = -2;
		goto OUT;
	}
	
	if( check_nbiot_attach(&comport,&hwinfo) < 0 )
	{
		zlog_error(c,"main_check_nbiot_attach failure");
		rv = -3;
		goto OUT;
	}
	
	if( set_nbiot_register(&comport,ip,port) < 0 )
	{
		zlog_error(c,"main_set_nbiot_register failure");
		rv = -4;
		goto OUT;
	}
	
	while( g_stop )
	{
		if(g_report)
		{
			if( nbiot_report_cloud(&comport, temp) < 0 )
			{
				zlog_error(c,"main_nbiot_report_cloud failure");
				rv = -5;
			}
			
			g_report = 0;
			
			alarm(DELAY_S);
		}
		
		sleep(1);
			
	}
	
	rv = 0;
	
OUT:	
	comport_close(&comport);

    zlog_fini();
	
	return rv;
}

void comport_init(comport_t *comport)
{
	comport->baudrate = 9600;
	comport->databits = 8;
	comport->parity = 'n';
	comport->stopbits = 1;
	snprintf(comport->modelname,sizeof(comport->modelname),"BC28");
	
	return ;
}
